package top.peng.concurrency.example.a_firstexperience;

import lombok.extern.slf4j.Slf4j;
import top.peng.concurrency.annoations.NotThreadSafe;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j// lombok包的
@NotThreadSafe
public class ConcurrencyTest {

    // 请求总数
    public static final int CLIENT_TOTAL = 5000;

    // 同时并发执行的线程总数
    public static final int THREAD_TOTAL = 400;

    private static int count = 0;

    public static void main(String[] args) throws InterruptedException {
        // 创建线程池
        ExecutorService executorService = Executors.newCachedThreadPool();
        // 使用信号量，设置并发执行线程数
        final Semaphore semaphore = new Semaphore(THREAD_TOTAL);
        // 设置闭锁数量，让main线程等待其他线程
        final CountDownLatch countDownLatch = new CountDownLatch(CLIENT_TOTAL);
        for (int i = 0; i < CLIENT_TOTAL; i++) {
            new AtomicInteger().incrementAndGet();
            executorService.execute(() -> {
                try {
                    semaphore.acquire();// 获取一个许可，所以可运行线程数量为 200/1=200
                    add();
                    semaphore.release();// 释放一个许可 (注意！上面获取了多少许可，这里就要释放多少，如果释放数小于获取数，会造成死锁)
                    countDownLatch.countDown();// 设置闭锁数量减一
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
        countDownLatch.await();// 等待其他线程执行结束再执行主线程
        executorService.shutdown();// 有序关闭线程池
        log.info("count: {}", count);
    }

    /**
     * 将静态成员变量加一
     */
    private static void add() {
        count++;
    }
}
